<?php

namespace Psg;

import('Db.Query');
import('Db.Connection');
import('Psg.Notifier');

/**
 * Główna klasa Autoryzacji i rejestracji
 * 
 * @author Michał Bocian <mhl.bocian@gmail.com>
 */
class Auth {

    /**
     * Zwraca połączenie z bazą danych
     * 
     * @return \Db\Connection Obiekt połączenia
     */
    private static function dbHandler() {
        $Db = \Db\Connection::Open();
        return $Db;
    }

    public static function isLoggedIn() {
        if (isset($_SESSION['nick'], $_SESSION['email'])) {
            if (!self::isBlockedUser($_SESSION['email']))
                return true;
            else
                return false;
        } else {
            return false;
        }
    }

    public static function isBlockedUser($email) {
        if (self::userExists($email)) {
            $Query = \Db\Query::Create('uzytk')->Select(['enable'])
                    ->Where(\Db\Operators::Create()->C('enable')->O('<>')->V('1'));
            if (count(self::dbHandler()->Query($Query)) == 1)
                return true;
            else
                return false;
        }else {
            return false;
        }
    }

    public static function setPermamentToken($email) {
        $token = substr(sha1($email . time()), 0, 30);
        $Query = \Db\Query::Create('uzytk')
                ->Update()
                ->Set(\Db\Operators::Create()
                        ->C('permlogin_token')->O('=')->V($token))
                ->Where(\Db\Operators::Create()->C('email')->O('=')->V($email));
        self::dbHandler()->Query($Query);
        return $token;
    }

    public static function permamentTokenExist($email, $token) {
        $Query = \Db\Query::Create('uzytk')
                ->Select()
                ->Where(\Db\Operators::Create()
                ->C('email')->O('=')->V($email)->O('and')
                ->C('permlogin_token')->O('=')->V($token));
        if (count(self::dbHandler()->Query($Query)) == 1)
            return true;
        else
            return false;
    }

    /**
     * Sprawdza istnienie zarejestrowanego użytkownika
     * 
     * @param type $email
     * @return boolean
     */
    public static function userExists($email) {
        $Query = \Db\Query::Create('uzytk')->Select()
                ->Where(\Db\Operators::Create()->C('email')->O('=')->V($email));
        $DbHandler = self::dbHandler();
        if (count($DbHandler->Query($Query)) == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Sprawdza czy istnieje rejestracja
     * 
     * @param type $email
     * @param type $nick
     * @return boolean
     */
    public static function registrationExist($email = null, $nick = null) {
        $DbHandler = self::dbHandler();
        $nmail = false;
        $nnick = false;
        if (!is_null($email)) {
            $QueryMail = \Db\Query::Create('registrations')->Select()
                    ->Where(\Db\Operators::Create()->C('email')->O('=')->V($email));
            if (count($DbHandler->Query($QueryMail)) == 1) {
                $nmail = true;
            } else {
                $nmail = false;
            }
        } else {
            $nmail = true;
        }
        if (!is_null($nick)) {
            $QueryNick = \Db\Query::Create('registrations')->Select()
                    ->Where(\Db\Operators::Create()->C('nick')->O('=')->V($nick));
            if (count($DbHandler->Query($QueryNick)) == 1) {
                $nnick = true;
            } else {
                $nnick = false;
            }
        } else {
            $nnick = true;
        }
        if ($nmail && $nnick) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Wysyła żądanie rejestracji
     * 
     * @param type $email
     * @param type $nick
     * @param type $state
     * @param type $city
     * @param type $date
     */
    public static function sendRegistration($email, $nick, $state, $city, $date) {
        $DbHandler = self::dbHandler();
        $Operators = \Db\Operators::Create()
                ->V($email)->O(',')
                ->V($nick)->O(',')
                ->V($state)->O(',')
                ->V($city)->O(',')
                ->V($date);
        $Cols = ['email', 'nick', 'state', 'city', 'dateofreg'];
        $Query = \Db\Query::Create('registrations')
                ->Insert($Operators, $Cols);
        $DbHandler->Query($Query);

        $Message = \View::factory('_mail_regRequest')->set('to', $nick);

        $Notifier = new Notifier();
        $Notifier->Send([$email], 'Rejestracja w Portalu PSG', $Message);
    }

    /**
     * Sprawdza czy istnieje uzytkownik o podanym nick'u
     * 
     * @param type $nick
     * @return boolean
     */
    public static function userNickExists($nick) {
        $Query = \Db\Query::Create('uzytk')->Select()
                ->Where(\Db\Operators::Create()->C('nick')->O('=')->V($nick));
        $DbHandler = self::dbHandler();
        if (count($DbHandler->Query($Query)) == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Wysyla do bazy TOKEN
     * 
     * @param type $email
     * @return boolean
     */
    public static function sendLoginReqToken($email) {
        if (self::userExists($email)) {
            $DbHandler = self::dbHandler();
            $DelQuery = \Db\Query::Create('loginReq')
                    ->Delete()
                    ->Where(\Db\Operators::Create()
                    ->C('email')->O('=')->V($email)
            );
            $DbHandler->Query($DelQuery);
            $token = substr(sha1($email . time()), 0, 30);
            $InsQuery = \Db\Query::Create('loginReq')->Insert(
                    \Db\Operators::Create()
                            ->V($email)
                            ->O(',')
                            ->V($token), ['email', 'token']);
            $DbHandler->Query($InsQuery);
            return $token;
        } else {
            return false;
        }
    }

    public static function loginTokenExists($email, $token) {
        if (self::userExists($email)) {
            $DbHandler = self::dbHandler();
            $Query = \Db\Query::Create('loginReq')
                    ->Select()
                    ->Where(\Db\Operators::Create()
                    ->C('email')->O('=')->V($email)->O('and')
                    ->C('token')->O('=')->V($token)
            );
            if (count($DbHandler->Query($Query) == 1))
                return true;
            else
                return false;
        } else {
            return false;
        }
    }

}
